package com.ljd.hosp.service.impl;

import com.alibaba.fastjson.JSON;
import com.ljd.hosp.repository.DepartmentRepository;
import com.ljd.hosp.service.DepartmentService;
import com.ljd.yygh.exception.YyghException;
import com.ljd.yygh.model.hosp.Department;
import com.ljd.yygh.result.ResultCodeEnum;
import com.ljd.yygh.vo.hosp.DepartmentQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Map<String, Object> paramMap) {
        String string = JSON.toJSONString(paramMap);
        Department department = JSON.parseObject(string, Department.class);
        String hoscode = department.getHoscode();
        String depcode = department.getDepcode();
        Department dept = departmentRepository.getByHoscodeAndDepcode(hoscode,depcode);
        if(null==dept) {
            department.setCreateTime(new Date());
        }else {
            department.setCreateTime(dept.getCreateTime());
        }
        department.setUpdateTime(new Date());
        department.setIsDeleted(0);
        departmentRepository.save(department);
    }

    @Override
    public Page<Department> listDept(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        Pageable pageable = PageRequest.of(page-1, limit);
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        Example<Department> example = Example.of(department, matcher);
        return departmentRepository.findAll(example, pageable);
    }

    @Override
    public void removeDept(String hoscode, String depcode) {
        Department department = departmentRepository.getByHoscodeAndDepcode(hoscode, depcode);
        if(department==null) {
            throw new YyghException(ResultCodeEnum.DEPT_NO);
        }
        departmentRepository.deleteById(department.getId());
    }
}
